package com.example.demo.controller;

import com.example.demo.Encrypt.EncryptPwd;
import com.example.demo.api.CommonResult;
import com.example.demo.entity.User;
import com.example.demo.Builder.saltBuilder;
import com.example.demo.Checker.interChecker;
import com.example.demo.DBmake.PostgreDB;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.sql.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
public class RegController {

    @RequestMapping(value = "/reg",method = RequestMethod.POST)
    public CommonResult login(@RequestBody User user){

        /****
         * 数据重验证 保证安全性
         */
        String username = user.getUsername();
        String userPwd = user.getPassword();
        interChecker t = new interChecker(".*\\W.*");

        if(!t.CheckString(username,1,11) || !t.CheckString(userPwd,1,16))
            return CommonResult.WrongNameOrPwd();

        PostgreDB Target = new PostgreDB();

        if(!Target.CheckUsername(username)) return CommonResult.usedUsername();

        /****
         * 生成用户盐数据
         * 生成加密密码
         */

        saltBuilder saltb = new saltBuilder(5);
        String salt = saltb.RandomSalt();
        String EncPwd = EncryptPwd.Encrypt(userPwd,salt);

        /****
         * 后端数据库写入
         */

        String sql = "INSERT INTO public.userinfo VALUES (DEFAULT,\'"+username+"\',\'"+EncPwd+"\',\'"+salt+"\')";
//        System.out.println(sql);
        if(!Target.updateItem(sql)) return CommonResult.ErrorDateBase();
        return CommonResult.success(username);
    }
}
